package com.cinemahorairerapido;

import java.io.IOException;
import java.net.URL;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.cinemahorairerapido.R;
import com.cinemahorairerapido.bean.Movie;
import com.cinemahorairerapido.controller.AllocineController;

public class MovieActivity extends Activity {

	// private static final int MENU_HELP = Menu.FIRST;
	//
	// private static final int DIALOG_HELP = 0;

	public final static String MOVIE = "movie";

	Movie currentMovie = null;

	Bitmap movieImage = null;

	TextView synopsisTextView;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.movie);

		// block rotation
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// get the row
		Bundle extras = getIntent().getExtras();

		currentMovie = (Movie) extras.getSerializable(MOVIE);

		// Set info
		// TextView movieNameTextView = (TextView)
		// findViewById(R.id.movieTitle);
		// movieNameTextView.setText(currentMovie.getMovieName());

		// title
		TextView movietitle = (TextView) findViewById(R.id.subtitlemovie);
		movietitle.setText(currentMovie.getMovieName());

		// runtime
		TextView runTimeText = (TextView) findViewById(R.id.runtimetext);
		Integer hours = currentMovie.getRuntime() / 3600;
		Integer remainder = currentMovie.getRuntime() % 3600;
		Integer minutes = remainder / 60;
		String runtime = String.format("%dh%02d", hours, minutes);
		runTimeText.setText(runtime);

		// rating
		TextView movieRating = (TextView) findViewById(R.id.movieRating);
		String pressRating = currentMovie.getPressRating() != null ? String.format("%.2f", currentMovie.getPressRating()) + "/5" : "N/A";
		String userRating = currentMovie.getUserRating() != null ? String.format("%.2f", currentMovie.getUserRating()) + "/5" : "N/A";

		String rating = getString(R.string.presserating) + " " + pressRating + " - " + //
				getString(R.string.userrating) + " " + userRating;
		movieRating.setText(rating);

		// realisator
		TextView directorTextView = (TextView) findViewById(R.id.movieRealisator);
		directorTextView.setText(currentMovie.getDirectors());

		// actor
		TextView actorsTextView = (TextView) findViewById(R.id.movieActors);
		actorsTextView.setText(currentMovie.getActors());

		// Genre
		String genre = "";
		for (String g : currentMovie.getGenre()) {
			genre += g + " ";
		}

		TextView movieGenreTextView = (TextView) findViewById(R.id.movieType);
		movieGenreTextView.setText(genre);

		synopsisTextView = (TextView) findViewById(R.id.movieSynopsisText);

		// try to get synopsis
		LoadSynopsisTask task = new LoadSynopsisTask();
		task.execute(currentMovie.getAllocineCode());

		LoadImageTask taskImage = new LoadImageTask();
		taskImage.execute(currentMovie.getAllocineCode());

	}

	private class LoadSynopsisTask extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... value) {

			String movieCode = value[0];

			try {
				String sysnopsis = AllocineController.getMovieSynopsis(movieCode);
				currentMovie.setSynopsis(sysnopsis);
			} catch (Exception e) {
				Log.d("MovieActivity", "unable to load sysnopsis due to : " + e.getLocalizedMessage());
				return 0;
			}

			return 1;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			// setProgressPercent(progress[0]);
		}

		@Override
		protected void onPostExecute(Integer result) {

			if (result == 1) {
				synopsisTextView.setText(currentMovie.getSynopsis());

			} else {
				synopsisTextView.setText(R.string.synopsiserror);
			}

		}
	}

	private class LoadImageTask extends AsyncTask<String, Integer, Integer> {

		@Override
		protected Integer doInBackground(String... value) {

			String movieCode = value[0];

			// set image
			try {

				movieImage = loadBitmap(currentMovie.getImageUrl());

			} catch (IOException e) {
				// ignore image loading problem
				return 0;
			}

			return 1;
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			// setProgressPercent(progress[0]);
		}

		@Override
		protected void onPostExecute(Integer result) {

			ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
			progressBar.setVisibility(View.GONE);

			ImageView imageView = (ImageView) findViewById(R.id.movieImage);
			imageView.setVisibility(View.VISIBLE);

			if (movieImage != null) {
				imageView.setImageBitmap(movieImage);
			} else {
				LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
				params.setMargins(0, 30, 0, 0);
				params.gravity = Gravity.CENTER_HORIZONTAL;
				imageView.setLayoutParams(params);

				// imageView.setMaxHeight(48);
				// imageView.setMaxWidth(48);
				imageView.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel));
			}

		}
	}

	public static Bitmap loadBitmap(String url) throws IOException {
		Bitmap bitmap = null;

		try {

			URL newurl = new URL(url);
			bitmap = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());

		} catch (IOException e) {
			Log.e("loadBitmap", "Could not load Bitmap from: " + url);
			throw e;
		}

		return bitmap;
	}

	public void finish(View v) {
		finish();
	}
}